package com.xidian.yunwudemo.service.impl;


import com.xidian.yunwudemo.service.CmdService;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Service
public class CmdServiceImpl implements CmdService {

    //本地：172.17.1.42
    //服务器：172.17.17.2
    @Override
    public String dockerService(String op, String cmd) throws IOException {
        Socket socket = new Socket("172.17.17.2", 26043);
        socket.setOOBInline(true);
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        try {
//            System.out.println("ready: " + op + " "+cmd);
            //向服务端发送op
            outputStream.write(op.getBytes(StandardCharsets.UTF_8));
            try {
                //获取返回结果
                byte[] rcv = new byte[1024];
                int len = inputStream.read(rcv);
                StringBuffer request = new StringBuffer();
                request.append(new String(rcv, 0, len, "UTF-8"));
                String info = request.toString();
                if (info.equals("ok")) {
                    //向服务端发送cmd
                    outputStream.write(cmd.getBytes(StandardCharsets.UTF_8));
                    try {
                        //获取返回结果
                        len = inputStream.read(rcv);
                        request = new StringBuffer();
                        request.append(new String(rcv, 0, len, "UTF-8"));
                        info = request.toString();
                        socket.shutdownOutput();
                        socket.close();
                        return info;
                    } catch (Exception e) {
                        e.printStackTrace();
                        socket.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            socket.close();
        }
        return "Run error!";
    }

}
//容器名字：
//        设备认证：UnifiedPlatform
//        用户认证：sxp1101
//        生物认证：lmr
//
//        常用命令：
//        启动容器：docker start 容器名
//        停止容器：docker stop 容器名
//        查看某个容器的状态：docker inspect 容器名

// docker container inspect 容器名 | grep "Status"